package com.cquprt.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 工具类
 */
@Slf4j
public class TcpSocket {
    /**
     * 功能：关流和关socket
     * @param bi 缓冲输入流
     * @param bo 缓冲输出流
     * @param server 服务端
     * @param client 客户端
     */
    public static void closeSAndC(BufferedReader br,BufferedWriter bw, BufferedInputStream bi, BufferedOutputStream bo, ServerSocket server, Socket client ){
        if (br!=null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bw!=null){
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (server!=null){
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (client!=null){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bi!=null){
            try {
                bi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bo!=null){
            try {
                bo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 功能：把以上方法重写，只关闭输入输出流
     */
    public static void closeSAndC(BufferedInputStream bi, BufferedOutputStream bo){
        closeSAndC(null,null,bi,bo,null,null);
    }
    /**
     * 功能：把以上方法重写，只关闭输入输出流
     */
    public static void closeSAndC(BufferedWriter bw, BufferedReader br){
        closeSAndC(br,bw,null,null,null,null);
    }
    //写字符串数据
    public static boolean writeData(String data,BufferedOutputStream bw){
        if (data!=null) {
            try {
                bw.write(data.getBytes());
                bw.flush();
                return true;
            } catch (IOException e) {
                log.info(e.getMessage());
            }
        }
        return false;
    }
    //写字节数据
    public static void writeData(byte[] data,BufferedOutputStream bo){
        try {
            bo.write(data);
            bo.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
